package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.util.Log
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.app.utls.TimeUtils.calculateTimeBreakpoints
import com.common.app.utls.TimeUtils.calculateTimeBreakpointsRounded
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.utils.JsonUtils
import com.common.base.utils.LogUtils
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils.getColor
import com.common.base.utils.ViewUtils.getString
import com.module.ble.data.bean.CusChartData
import com.module.ble.db.table.UserSleepInfo
import com.module.ble.repo.HeartRateRepo
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.groupSleepDataByQualityAndTime
import com.module.ble.widget.CandlestickChart
import com.module.ble.widget.SleepHrCurveChart
import com.module.ble.widget.SleepHrCurveNewChart
import com.module.ble.widget.SleepHrvCandlestickChart
import com.module.ble.widget.SleepOptimalRangeProgressBar
import com.module.ble.widget.SleepStageChart
import com.module.overview.R
import kotlin.random.Random

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/11
 *
 * 描述：睡眠时段卡片
 *
 * 修订历史：
 *
 */
class OvSleepPeriodCardNewProvider(time:Long,
                                   override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SLEEP_TOTAL_PERIOD,
                                   override val layoutId: Int = R.layout.overview_sleep_period_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private val sleepData = mutableListOf<CusChartData>()

    var points = mutableListOf<String>()

    private val sleepHrvCurveData = mutableListOf<CusChartData>()
    private var sleepHrCurveChart: SleepHrCurveNewChart? = null
    private val sleepHrvCandlestickData = mutableListOf<CusChartData>()
    private var sleepHrvCandlestickChart: SleepHrvCandlestickChart? = null
    private var sleepOxyCurveChart: SleepHrCurveChart? = null

    private var curTime = time


    var totalDuration = 0L//睡眠总时长，单位：分钟
    var awakeDuration = 0L//清醒时长，单位：分钟
    var lightDuration = 0L//浅睡时长，单位：分钟
    var remDuration = 0L//快速眼动时长，单位：分钟
    var deepDuration = 0L//深睡时长，单位：分钟

    var hrSplice = getString(R.string.common_times_per_minute_splice)

    init {
        val currentTime = System.currentTimeMillis()
        val startOfDay = currentTime - (currentTime % (24 * 60 * 60 * 1000)) // 当天0点时间戳

        for (index in 0 until 37) {
            val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
            val timestamp = startOfDay + timeOffset

            // 根据实际压力数据设置值（0-100）
            val minValue = when {
                index < 12 -> (10 + (30..70).random()).toFloat() // 0-6点
                index < 24 -> (30..80).random().toFloat() // 6-12点
                else -> (30..80).random().toFloat() // 12-24点
            }

            sleepHrvCandlestickData.add(
                CusChartData(
                    createdTime = timestamp,
                    minValue = (30..minValue.toInt()).random().toFloat(),
                    mValue = minValue,
                    dayNum = 0
                )
            )
        }

        for (index in 0 until 19) {
            val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
            val timestamp = startOfDay + timeOffset

            // 根据实际压力数据设置值（0-100）
            val minValue = when {
                index < 12 -> (90..97).random().toFloat() // 0-6点
                index < 24 -> (90..92).random().toFloat() // 6-12点
                else -> (93..100).random().toFloat() // 12-24点
            }

            sleepHrvCurveData.add(
                CusChartData(
                    createdTime = timestamp,
                    minValue = 0f,
                    mValue = minValue,
                    dayNum = 0
                )
            )
        }


//        sleepHrCurveData[0].minValue = 20f
//        sleepHrCurveData[0].mValue = 110f
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {

        val sleepStageChart = helper.getView<SleepStageChart>(R.id.sleepStageChart)

        // 设置数据
        sleepStageChart.setRowCount(4)
//        sleepStageChart.setSleepStageData(sleepData)

        // 设置触摸监听
        sleepStageChart.setOnSleepStageTouchListener (object :
            SleepStageChart.OnSleepStageTouchListener{
            override fun onStageTouch(stageData: CusChartData, stageName: String) {
                // 处理触摸事件
                Log.d("SleepChart", "触摸了 $stageName，时长：${stageData.timeLong}分钟")
                helper.setGone(R.id.tvSleepStaging,false)
                helper.setText(R.id.tvSleepStaging,"${stageName}时长：${stageData.timeLong}分钟")
            }

            override fun onTouchReleased() {
                helper.setGone(R.id.tvSleepStaging,true)

            }

        })

//        sleepHrCurveChart?.setYRangeBackground(startValue = 55f,endValue = 65f,backgroundColor = getColor(R.color.c_f7ebf2))
//        sleepHrCurveChart?.setTimeLabels(points)
//        // 设置Y轴阶段
//        sleepHrCurveChart?.setYAxisStages(
//            floatArrayOf(30f, 65f, 120f), // 阶段分界点
//        )
//        sleepHrCurveChart?.setBasicValue(75f)
//        sleepHrCurveChart?.setData(sleepHrvCandlestickData)


//        sleepHrvCandlestickChart?.setXAxisSolidLineEnabled(true)
        sleepHrvCandlestickChart?.setTimeLabels(points)
        // 设置Y轴阶段
        sleepHrvCandlestickChart?.setYAxisStages(
            floatArrayOf(0f, 70f, 150f), // 阶段分界点
        )
        sleepHrvCandlestickChart?.setBasicValue(55f)
        sleepHrvCandlestickChart?.setData(sleepHrvCandlestickData)


        sleepOxyCurveChart?.setYRangeBackground(startValue = 95f,endValue = 100f,backgroundColor = getColor(R.color.c_f7ebf6))
        sleepOxyCurveChart?.setTimeLabels(points)
        // 设置Y轴阶段
        sleepOxyCurveChart?.setYAxisStages(
            floatArrayOf(90f, 95f, 100f), // 阶段分界点
        )
        sleepOxyCurveChart?.setBasicValue(97f)
        sleepOxyCurveChart?.setData(sleepHrvCurveData)

        val timeTemp = TimeUtils.getTimeRangeForSleep(curTime)
        doOnIOThread {
            SleepInfoRepo.instance.findByTimeRangeByNight(timeTemp.first, timeTemp.second)?.let {listIt->
                listIt.sortedBy { it.createdTime }//按时间排序（升序）
                listIt.isNullOrEmpty().no {
                    getSleepHr(listIt.firstOrNull()?.createdTime?:0,listIt.lastOrNull()?.createdTime?:0)
                }
//                LogUtils.d("OvSleepPeriodCardProvider", "YQ: allSleepData ${JsonUtils.toJson(listIt)}")
                initClassDuration()

                sleepData.clear()
                if (listIt.isNotEmpty()) {
                    val groupedSleepData = groupSleepDataByQualityAndTime(listIt)
                    sleepData.addAll(groupedSleepData)
                    sleepData.forEach {sleepDataIt->
                        totalDuration += if (sleepDataIt.status==1||sleepDataIt.status==2||sleepDataIt.status==3) sleepDataIt.timeLong else 0
                        when (sleepDataIt.status) {// 睡眠质量 0,清醒(离床) 1:快速眼动 2:浅睡 3:深睡 4:未佩戴  101:小睡（自用） -999：未知（自用）
                            0 -> awakeDuration += sleepDataIt.timeLong  // 清醒
                            1 -> remDuration += sleepDataIt.timeLong    // 快速眼动
                            2 -> lightDuration += sleepDataIt.timeLong  // 浅睡
                            3 -> deepDuration += sleepDataIt.timeLong   // 深睡
                        }
                    }
                    points = calculateTimeBreakpointsRounded(listIt.first().createdTime, listIt.last().createdTime) as MutableList<String>
                }

                doOnUiThread {
                    helper.setText(R.id.tvTotalDuration, TimeUtils.formatTime(((totalDuration- awakeDuration)*60*1000), showHour = true, showMin = true))
                    sleepStageChart.setSleepStageData(sleepData)
                    helper.setText(R.id.tvTimeOne,points[0])
                    helper.setText(R.id.tvTimeTwo,points[1])
                    helper.setText(R.id.tvTimeThree,points[2])
                    helper.setText(R.id.tvTimeFour,points[3])
                    helper.setText(R.id.tvTimeFive,points[4])



                    helper.getView<SleepOptimalRangeProgressBar>(R.id.spbAwake).apply {//清醒进度条
                        setProgress(((awakeDuration.toFloat() / totalDuration) * 100f).toInt())
                        // 设置最佳区间
                        setOptimalRange(0.5f, 10f)
                    }
                    helper.getView<SleepOptimalRangeProgressBar>(R.id.spbRem).apply {//快速眼动进度条
                        setProgress(((remDuration.toFloat() / totalDuration) * 100f).toInt())
                        // 设置最佳区间
                        setOptimalRange(20f,25f)
                    }
                    helper.getView<SleepOptimalRangeProgressBar>(R.id.spbLight).apply {//浅睡进度条
                        setProgress(((lightDuration.toFloat() / totalDuration) * 100f).toInt())
                        // 设置最佳区间
                        setOptimalRange(50f,60f)
                    }
                    helper.getView<SleepOptimalRangeProgressBar>(R.id.spbDeep).apply {//深睡进度条
                        setProgress(((deepDuration.toFloat() / totalDuration) * 100f).toInt())
                        // 设置最佳区间
                        setOptimalRange(15f, 25f)
                    }

                    helper.setText(R.id.tvAwakeDuration,TimeUtils.formatTime((awakeDuration*60*1000), showHour = true, showMin = true))
                    helper.setText(R.id.tvRemDuration,TimeUtils.formatTime((remDuration*60*1000), showHour = true, showMin = true))
                    helper.setText(R.id.tvLightDuration,TimeUtils.formatTime((lightDuration*60*1000), showHour = true, showMin = true))
                    helper.setText(R.id.tvDeepDuration,TimeUtils.formatTime((deepDuration*60*1000), showHour = true, showMin = true))
                }

            }
        }
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        sleepHrCurveChart = viewHolder.getView(R.id.sleepHrCurveChart)
        // 设置触摸监听
        sleepHrCurveChart?.setOnBarTouchListener(object : SleepHrCurveNewChart.OnBarTouchListener {
            override fun onBarTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String
            ) {
                SpanUtils.create()
                    .addSection(maxValue.toInt().toString())
//                    .addForeColorSection(maxValue.toInt().toString(), ViewUtils.getColor(R.color.c_7f7f7f))
                    .setAbsSize(hrSplice, 14)
                    .setStyle(hrSplice, Typeface.NORMAL)
                    .showIn(viewHolder.getView(R.id.tvHrTouchValue))

                sleepHrCurveChart?.let {
                    viewHolder.setText(R.id.tvHrTouchValueHint,"${TimeUtils.getHourMinute(it.getData()[index].createdTime)}-${TimeUtils.getHourMinute(it.getData()[index].endTime)}")
                }

                viewHolder.setVisible(R.id.totalHrTouchValue, true)
            }

            override fun onTouchReleased() {
                // 处理触摸释放事件
                viewHolder.setVisible(R.id.totalHrTouchValue, false)
            }
        })
        sleepHrvCandlestickChart = viewHolder.getView(R.id.sleepHrvCandlestickChart)
        sleepOxyCurveChart = viewHolder.getView(R.id.sleepOxyCurveChart)
        super.onViewHolderCreated(viewHolder, viewType)
    }

    private fun initClassDuration(){
        totalDuration = 0L//睡眠总时长，单位：分钟
        awakeDuration = 0//清醒时长，单位：分钟
        lightDuration = 0//浅睡时长，单位：分钟
        remDuration = 0//快速眼动时长，单位：分钟
        deepDuration = 0//深睡时长，单位：分钟
    }

    private fun getSleepHr(startTime:Long, endTime:Long){
        if (startTime <=0 ||endTime <=0) return

        //睡眠心率
        HeartRateRepo.instance.findByTimeRange(startTime, endTime)?.let {listIt->
            val listItStr = JsonUtils.toJson(listIt)
            // 创建48个时间区间块的CusChartData数组
            val sleepHrData = mutableListOf<CusChartData>()
            val timeDuration = endTime - startTime
            val intervalDuration = timeDuration / 24 // 每个时间区间的时长

            // 初始化48个时间区间块
            for (i in 0 until 24) {
                val intervalStartTime = startTime + (i * intervalDuration)
                val intervalEndTime = startTime + ((i + 1) * intervalDuration)
                sleepHrData.add(
                    CusChartData(
                        createdTime = intervalStartTime,
                        endTime = intervalEndTime,
                        minValue = 0f,
                        mValue = 0f,
                        dayNum = 0
                    )
                )
            }

            val sleepHrDataInitStr = JsonUtils.toJson(sleepHrData)

            // 将listIt数组的数据根据createdTime分配到对应的时间区间块
            listIt.sortedBy { it.createdTime }.forEach { heartRateData ->
                // 计算该心率数据属于哪个时间区间块
                val timeOffset = heartRateData.createdTime - startTime
                val intervalIndex = (timeOffset / intervalDuration).toInt()

                // 确保索引在有效范围内
                if (intervalIndex in 0 until 24) {
                    val currentData = sleepHrData[intervalIndex]
                    // 将心率值累加到对应区间块的mValue中
                    if (currentData.mValue == 0f) {
                        // 如果是第一个数据，直接赋值
                        currentData.mValue = heartRateData.heartRate.toFloat()
                    } else {
                        // 如果已有数据，可以选择取平均值或最大值等策略
                        // 这里采用平均值策略
                        currentData.mValue = (currentData.mValue + heartRateData.heartRate.toFloat()) / 2f
                    }
                }
            }


             val points = calculateTimeBreakpointsRounded(startTime, endTime) as MutableList<String>

            val minTemp = ((listIt.minOfOrNull { it.heartRate } ?: 30f).toFloat())
            val maxTemp = ((listIt.maxOfOrNull { it.heartRate } ?: 125f).toFloat())
            val theDayAverage = if (listIt.isNotEmpty()) {
                listIt.map { it.heartRate }.average().toFloat()
            } else {
                60f
            }

            val sleepHrDataStr = JsonUtils.toJson(sleepHrData)
            doOnUiThread {
                sleepHrCurveChart?.setYRangeBackground(startValue = 55f,endValue = 65f,backgroundColor = getColor(R.color.c_f7ebf2))
                sleepHrCurveChart?.setTimeLabels(points)
                // 设置Y轴阶段
                sleepHrCurveChart?.setYAxisStages(
                    floatArrayOf(minTemp-10f, ((maxTemp-minTemp)/2).toInt()+minTemp, maxTemp+10f), // 阶段分界点
                )

                sleepHrCurveChart?.setBasicValue(theDayAverage)

                //测试数据
                val mTestList: List<CusChartData> = JsonUtils.fromJsonList("[{\"createdTime\":1755182520000,\"dayNum\":0,\"endTime\":1755185605000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":58.132805,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755185605000,\"dayNum\":0,\"endTime\":1755188690000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":74.115265,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755188690000,\"dayNum\":0,\"endTime\":1755191775000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":49.54845,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755191775000,\"dayNum\":0,\"endTime\":1755194860000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":0.0,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755194860000,\"dayNum\":0,\"endTime\":1755197945000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":59.31672,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755197945000,\"dayNum\":0,\"endTime\":1755201030000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":0.0,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755201030000,\"dayNum\":0,\"endTime\":1755204115000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":0.0,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755204115000,\"dayNum\":0,\"endTime\":1755207200000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":80.5,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755207200000,\"dayNum\":0,\"endTime\":1755210285000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":64.0,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755210285000,\"dayNum\":0,\"endTime\":1755213370000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":65.5,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755213370000,\"dayNum\":0,\"endTime\":1755216455000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":77.5,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0},{\"createdTime\":1755216455000,\"dayNum\":0,\"endTime\":1755219540000,\"mColor\":0,\"mOrder\":0,\"mProportion\":0.0,\"mValue\":0.0,\"minValue\":0.0,\"selectBg\":false,\"status\":0,\"timeLong\":0}]")
                sleepHrCurveChart?.setData(sleepHrData)
            }

        }
    }

    fun get7NightsAverageValue(){//近7晚心率平均

    }
}